package com.fulihui.wgj.admin.integration.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.builder.web.PageViewBuilder;
import com.fulihui.common.constants.QrcodeConstants;
import com.fulihui.common.request.rpc.AppRequest;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.result.web.PageView;
import com.fulihui.common.result.web.Result;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.wgj.admin.api.material.vo.MaterialNewsItemVO;
import com.fulihui.wgj.admin.api.material.vo.MaterialSingleVO;
import com.fulihui.wgj.admin.api.qrcode.excelmodel.QrcodeStatExcelModel;
import com.fulihui.wgj.admin.api.qrcode.request.*;
import com.fulihui.wgj.admin.api.qrcode.vo.QrcodeCreateVO;
import com.fulihui.wgj.admin.api.qrcode.vo.QrcodeLabelInfoVO;
import com.fulihui.wgj.admin.api.qrcode.vo.QrcodeStatDetailVO;
import com.fulihui.wgj.admin.api.qrcode.vo.QrcodeStatVO;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.integration.MaterialServiceClient;
import com.fulihui.wgj.admin.integration.ParamQrcodeServiceClient;
import com.fulihui.wgj.facade.dto.*;
import com.fulihui.wgj.facade.request.qrcode.*;
import com.fulihui.wgj.facade.result.qrcode.WxQrcodePageResult;
import com.fulihui.wgj.facade.result.qrcode.WxQrcodeStatDetailPageResult;
import com.fulihui.wgj.facade.service.qrcode.WxParamQrcodeService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static com.fulihui.common.enums.CustomMsgTypeEnum.*;

/**
 * @author: Levon
 * @date: 2018-07-09 14:14
 */
@Service
public class ParamQrcodeServiceClientImpl implements ParamQrcodeServiceClient {

    @Reference(version = "1.0.0")
    private WxParamQrcodeService wxParamQrcodeService;

    @Autowired
    private MaterialServiceClient materialServiceClient;

    @Autowired
    AdminProperties adminProperties;

    /**
     * 创建参数二维码
     *
     * @param request
     * @return
     */
    @Override
    public Result<QrcodeCreateVO> saveParamQrcodeInfo(QrcodeCreateRequest request) {

        WxParamQrcodeSaveRequest saveRequest = new WxParamQrcodeSaveRequest();
        saveRequest.setAppId(request.getAppId());
        saveRequest.setSceneDescribe(request.getQrcodeName());
        saveRequest.setSceneStr(request.getSceneStr());
        saveRequest.setMsgType(request.getMsgType());
        saveRequest.setContent(request.getContent());
        saveRequest.setChannelLabel(request.getChannelLabel());
        SimpleResult<WxParamQrcodeInfoDTO> baseResult = wxParamQrcodeService.saveParamQrcodeInfo(saveRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {

            QrcodeCreateVO createVO = new QrcodeCreateVO();
            createVO.setShowQrcodeUrl(QrcodeConstants.SHOW_QRCODE + baseResult.getData().getTicket());
            return JsonResultBuilder.succ(createVO);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    /**
     * 查询分页
     *
     * @param request
     * @return
     */
    @Override
    public PageView<QrcodeStatVO> queryPage(QrcodeQueryRequest request) {

        WxQrcodePageQueryRequest qrcodeQueryRequest = new WxQrcodePageQueryRequest();
        qrcodeQueryRequest.setStartDate(request.getStartDate());
        qrcodeQueryRequest.setEndDate(request.getEndDate());
        qrcodeQueryRequest.setSceneDescribe(request.getQrcodeName());
        qrcodeQueryRequest.setAppId(request.getAppId());
        qrcodeQueryRequest.setPage(request.getPage());
        qrcodeQueryRequest.setRows(request.getRows());

        WxQrcodePageResult pageResult = wxParamQrcodeService.pageQueryStatistics(qrcodeQueryRequest);

        List<QrcodeStatVO> values = Lists.newArrayList();
        if (RpcResultCheckUtil.isSuccess(pageResult)) {
            List<WxQrcodeEventStatDTO> dtos = pageResult.getValue();
            if (!CollectionUtils.isEmpty(dtos)) {
                for (WxQrcodeEventStatDTO statDTO : dtos) {
                    QrcodeStatVO statVO = new QrcodeStatVO();
                    statVO.setCreateDate(DateUtils.format(statDTO.getGmtCreate(), DateUtils.noSecondFormat));
                    statVO.setScanCount(statDTO.getScanCount());
                    statVO.setSubscribeCount(statDTO.getSubscribeCount());
                    statVO.setSceneId(statDTO.getSceneStr());
                    statVO.setSceneDescribe(statDTO.getSceneDescribe());
                    statVO.setReplyInfoId(statDTO.getReplyInfoId());
                    statVO.setQrcodeImgUrl(QrcodeConstants.SHOW_QRCODE + statDTO.getTicket());
                    values.add(statVO);
                }
            }
        }
        return PageViewBuilder.build(values, pageResult.getPage(), pageResult.getRows(), pageResult.getTotalRows());
    }


    /**
     * 详情分页
     *
     * @param request
     * @return
     */
    @Override
    public PageView<QrcodeStatDetailVO> queryDetailPage(QrcodeQueryDetailRequest request) {

        WxQrcodeStatDetailPageQueryRequest queryRequest = new WxQrcodeStatDetailPageQueryRequest();
        queryRequest.setStartDate(request.getStartDate());
        queryRequest.setEndDate(request.getEndDate());
        queryRequest.setSceneId(request.getSceneId());
        queryRequest.setAppId(request.getAppId());
        queryRequest.setPage(request.getPage());
        queryRequest.setRows(request.getRows());

        List<QrcodeStatDetailVO> detailVOS = Lists.newArrayList();

        WxQrcodeStatDetailPageResult pageResult = wxParamQrcodeService.pageQueryDetailStatistics(queryRequest);
        if (RpcResultCheckUtil.isSuccess(pageResult)) {
            List<WxQrcodeEventStatDetailDTO> value = pageResult.getValue();
            if (!CollectionUtils.isEmpty(value)) {
                for (WxQrcodeEventStatDetailDTO detailDTO : value) {
                    QrcodeStatDetailVO detailVO = new QrcodeStatDetailVO();
                    detailVO.setCreateDate(detailDTO.getGmtAttention());
                    detailVO.setTotalScan(detailDTO.getSubscribeCount() + detailDTO.getScanOldUserCount());
                    detailVO.setScanCount(detailDTO.getScanOldUserCount());
                    detailVO.setTotalPersonScan(detailDTO.getScanUserCount());
                    detailVO.setSubscribeCount(detailDTO.getSubscribeCount());
                    detailVO.setUnsubscribeCount(detailDTO.getUnsubscribeCount());
                    detailVOS.add(detailVO);
                }
            }
        }
        return PageViewBuilder.build(detailVOS, pageResult.getPage(), pageResult.getRows(), pageResult.getTotalRows());
    }

    @Override
    public List<QrcodeStatExcelModel> exportDetail(QrcodeExportDetailRequest request) {
        WxQrcodeStatDetailQueryRequest queryRequest = new WxQrcodeStatDetailQueryRequest();
        queryRequest.setAppId(request.getAppId());
        queryRequest.setSceneId(request.getSceneId());
        queryRequest.setStartDate(request.getStartDate());
        queryRequest.setEndDate(request.getEndDate());
        SimpleResult<List<WxQrcodeEventStatDetailDTO>> simpleResult = wxParamQrcodeService.queryDetailStatistics(queryRequest);

        List<QrcodeStatExcelModel> statExcelModels = Lists.newArrayList();

        if (RpcResultCheckUtil.isSuccess(simpleResult)) {
            List<WxQrcodeEventStatDetailDTO> datas = simpleResult.getData();
            if (!CollectionUtils.isEmpty(datas)) {
                for (WxQrcodeEventStatDetailDTO detailDTO : datas) {
                    QrcodeStatExcelModel excelModel = new QrcodeStatExcelModel();
                    excelModel.setTotalScan(detailDTO.getSubscribeCount() + detailDTO.getScanOldUserCount());
                    excelModel.setScanCount(detailDTO.getScanOldUserCount());
                    excelModel.setCreateDate(detailDTO.getGmtAttention());
                    excelModel.setTotalPersonScan(detailDTO.getScanUserCount());
                    excelModel.setSubscribeCount(detailDTO.getSubscribeCount());
                    excelModel.setUnsubscribeCount(detailDTO.getUnsubscribeCount());
                    statExcelModels.add(excelModel);
                }
            }
        }
        return statExcelModels;
    }

    /**
     * 查询回复素材
     *
     * @param replyGetRequest
     * @return
     */
    @Override
    public Result<MaterialSingleVO> queryReplyById(QrcodeReplyGetRequest replyGetRequest) {

        Long replyId = replyGetRequest.getReplyId();

        MaterialSingleVO singleVO = new MaterialSingleVO();

        if (replyGetRequest.getReplyId() != null && replyGetRequest.getReplyId() > 0) {
            WxQrcodeReplyQueryOneRequest request = new WxQrcodeReplyQueryOneRequest();
            request.setAppId(replyGetRequest.getAppId());
            request.setId(replyId);
            SimpleResult<WxQrcodeReplyInfoDTO> simpleResult = wxParamQrcodeService.queryOneReplyInfo(request);
            if (RpcResultCheckUtil.isSuccess(simpleResult)) {
                WxQrcodeReplyInfoDTO data = simpleResult.getData();

                if (StringUtils.equals(text.getCode(), data.getMsgType())) {
                    singleVO.setTextContent(data.getContent());
                } else if (StringUtils.equals(image.getCode(), data.getMsgType())) {
                    String content = data.getContent();
                    WxMaterialDTO material = materialServiceClient.queryMaterialById(content);
//                    WxMaterialDTO material = JSON.parseObject(content, WxMaterialDTO.class);
                    singleVO.setImgUrl(adminProperties.getImgproxy() + material.getImageUrl());
                    singleVO.setMediaId(material.getMediaId());
                    singleVO.setUpdateTime(DateUtils.format(material.getUpdateTime(), DateUtils.noSecondFormat));
                } else if (StringUtils.equals(mpnews.getCode(), data.getMsgType())) {
                    String content = data.getContent();
                    WxMaterialDTO material = materialServiceClient.queryMaterialById(content);
//                    WxMaterialDTO material = JSON.parseObject(content, WxMaterialDTO.class);
                    singleVO.setMediaId(material.getMediaId());
                    singleVO.setUpdateTime(DateUtils.format(material.getUpdateTime(), DateUtils.noSecondFormat));
                    String items = material.getContent();
                    List<MaterialNewsItemVO> newsItemVOS = materialServiceClient.parse(items);
                    singleVO.setItems(newsItemVOS);
                }
                singleVO.setType(data.getMsgType());
            }
        }

        WxQrcodeInfoQueryRequest infoQueryRequest = new WxQrcodeInfoQueryRequest();
        infoQueryRequest.setAppId(replyGetRequest.getAppId());
        infoQueryRequest.setSceneStr(replyGetRequest.getSceneId());
        SimpleResult<WxParamQrcodeInfoDTO> result = wxParamQrcodeService.queryParamQrcodeInfo(infoQueryRequest);
        if (RpcResultCheckUtil.isSuccess(result) && result.getData() != null) {
            WxParamQrcodeInfoDTO data = result.getData();
            singleVO.setShowQrcodeUrl(QrcodeConstants.SHOW_QRCODE + data.getTicket());
            singleVO.setQrcodeName(data.getSceneDescribe());
            singleVO.setSceneStr(data.getSceneStr());
            singleVO.setChannelLabel(data.getChannelLabel());
        }

        return JsonResultBuilder.succ(singleVO);
    }

    /**
     * 参数二维码回复编辑请求
     *
     * @param replyEditRequest
     * @return
     */
    @Override
    public Result<Boolean> saveOrUpdate(QrcodeReplyEditRequest replyEditRequest) {
        WxQrcodeReplyRequest replyRequest = new WxQrcodeReplyRequest();
        replyRequest.setContent(replyEditRequest.getContent());
        replyRequest.setId(replyEditRequest.getId());
        replyRequest.setMsgType(replyEditRequest.getMsgType());
        replyRequest.setSceneStr(replyEditRequest.getSceneStr());
        replyRequest.setAppId(replyEditRequest.getAppId());
        BaseResult baseResult = wxParamQrcodeService.saveReplyInfo(replyRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    /**
     * 删除回复
     *
     * @param replyDelRequest
     * @return
     */
    @Override
    public Result<Boolean> delReply(QrcodeReplyDelRequest replyDelRequest) {

        WxQrcodeReplyDeleteRequest deleteRequest = new WxQrcodeReplyDeleteRequest();
        deleteRequest.setId(replyDelRequest.getId());
        BaseResult baseResult = wxParamQrcodeService.deleteReplyInfo(deleteRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public Result<List<QrcodeLabelInfoVO>> queryQrcodeLabel(String appId) {
        List<QrcodeLabelInfoVO> labelInfoVOS = Lists.newArrayList();
        AppRequest appRequest = new AppRequest();
        appRequest.setAppId(appId);
        SimpleResult<List<WxParamQrcodeInfoDTO>> simpleResult = wxParamQrcodeService.querySceneHasLabel(appRequest);
        if (RpcResultCheckUtil.isSuccess(simpleResult)) {
            List<WxParamQrcodeInfoDTO> datas = simpleResult.getData();
            if (!CollectionUtils.isEmpty(datas)) {
                for (WxParamQrcodeInfoDTO data : datas) {
                    QrcodeLabelInfoVO labelInfoVO = new QrcodeLabelInfoVO();
                    labelInfoVO.setChannelName(data.getChannelName());
                    labelInfoVO.setSceneStr(data.getSceneStr());
                    labelInfoVOS.add(labelInfoVO);
                }
            }
        } else {
            return JsonResultBuilder.fail(simpleResult.getErrcode(), simpleResult.getErrmsg());
        }
        return JsonResultBuilder.succ(labelInfoVOS);
    }
}
